/**
 * 消息模块 store
 */

import * as sessionKeys from "../../utils/keysManage/sessionKeys";
import { getUnReadCount } from "../../api/message/message.api";

const { MSG_UNREAD_COUNT } = sessionKeys;

const state = {
  // 消息未读数量
  unReadCount: window.sessionStorage.getItem(MSG_UNREAD_COUNT)
    ? Number(window.sessionStorage.getItem(MSG_UNREAD_COUNT))
    : 0,
};

const mutations = {
  setUnReadCount(state, count) {
    state.unReadCount = count;
    window.sessionStorage.setItem(MSG_UNREAD_COUNT, state.unReadCount);
  },
};

const getters = {};

const actions = {
  getUnReadCount({ commit }) {
    return new Promise((resolve, reject) => {
      getUnReadCount()
        .then((res) => {
          commit("setUnReadCount", res.data || 0);
          resolve(res);
        })
        .catch((err) => {
          console.error("getUnReadCount error: ", err);
          reject(err);
        });
    });
  },
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
};
